import React, { ChangeEvent, useRef } from "react";
import style from "./index.module.scss";
import TextArea from "antd/es/input/TextArea";
import { Avatar, Space, Tag } from "antd";
import { SEVER_URL, formats, modules } from "@/configs/constant";
import { UserOutlined } from "@ant-design/icons";
import { useStore } from "@/zustand/store";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

export interface ICommentRoot {
  content: string;
  createTime: string;
  id: number;
  userId: number;
  postId: number;
  rootId: number;
  type: number;
  replyUserName: number;
  userName: string;
  updateTime: string;
  userHead: string;
  replyUserHead: string;
  replyUserId?: number;
  commentResultList: ICommentRoot[];
}
interface ICommentReply extends Omit<ICommentRoot, "commentResultList"> {}

type TCommentRoot = {
  userId: number;
  review: ICommentRoot;
  handleDel?: (commentId: number) => void;
  handleReply?: (rootId: number, rvId: number, postId: number) => void;
  isAuthor?: number | string;
};
type TCommentReply = Omit<IComments, "reviewList"> & {
  reply: ICommentReply;
};
interface IReview {
  textareaRef?: React.RefObject<ReactQuill>;
  textRef?: React.RefObject<HTMLDivElement>;
  value?: string;
  reviewList?: ICommentRoot[];
  onChange?: (val: ChangeEvent<HTMLTextAreaElement>) => void;
  onPublish?: () => void;
  isAuthor?: number | string;
  handleReply?: (rootId: number, rvId: number, postId: number) => void;
  handleDel?: (commentId: number) => void;
  contentCourse?: string;
  handleChangeValue?: (value: string) => void;
}
interface IComments
  extends Omit<IReview, "value" | "onChange" | "onPublish" | "textareaRef"> {
  handleDel?: (commentId: number) => void;
  userId: number;
}
export default function handleReplyReview(props: IReview) {
  const {
    reviewList,
    textRef,
    value,
    textareaRef,
    onChange,
    onPublish,
    handleReply,
    handleDel,
    isAuthor,
    contentCourse,
    handleChangeValue,
  } = props;
  const handleFocus = () => {
    textareaRef?.current && textareaRef.current.focus();
  };
  const handleBlur = () => {
    textareaRef?.current && textareaRef.current.blur();
  };
  const userId = useStore((store) => store.userId);

  const module = {
    toolbar: [
      [{ header: [1, 2, 3, false] }],
      ["bold", "italic", "underline", "strike"],
      ["blockquote", "code-block"],
      [{ list: "ordered" }, { list: "bullet" }],
      ["link", "image"], // 默认图片按钮
      ["clean"],
    ],
  };

  return (
    <div className={style["reviewContainer"]}>
      <div className={style["title"]}>
        <h2>评论</h2>
      </div>
      <div
        className={style["contentBox"]}
        onFocus={handleFocus}
        onBlur={handleBlur}
        tabIndex={1}
        ref={textRef}
      >
        <div className={style["contentArea"]}>
          <div className={style["edit"]}>
            <div className={style["brtRoot"]}>
              {/* <TextArea
                placeholder="你渴望拥有力量吗？评论让力量更强大"
                autoSize
                className={style["brtEditor"]}
                value={value}
                onChange={(e) => onChange(e)}
                ref={textareaRef}
              /> */}
              <ReactQuill
                placeholder="请输入你想评论的内容"
                theme="snow"
                value={value}
                onChange={handleChangeValue}
                formats={formats}
                modules={module}
                className={style["brtEditor"]}
                ref={textareaRef}
              />
            </div>
          </div>
        </div>
      </div>
      <div className={style["publishBtn"]}>
        <span className={style["text"]} onClick={onPublish}>
          发布
        </span>
      </div>
      {/* TODO:评论区 */}
      <Comments
        reviewList={reviewList}
        handleReply={handleReply}
        userId={userId}
        handleDel={handleDel}
        isAuthor={isAuthor}
      />
    </div>
  );
}
const Comments = (props: IComments) => {
  const { reviewList, handleReply, userId, handleDel, isAuthor } = props;
  return (
    <div className={style["contents"]}>
      <div className={style["commentThreadRender"]}>
        {reviewList?.map((item) => (
          <div key={item.id}>
            <CommnetRoot
              review={item}
              handleReply={handleReply}
              userId={userId}
              handleDel={handleDel}
              isAuthor={isAuthor}
            />
            {item.commentResultList.map((reply) => (
              <CommentReply
                reply={reply}
                handleReply={handleReply}
                userId={userId}
                handleDel={handleDel}
                isAuthor={isAuthor}
              />
            ))}
          </div>
        ))}
      </div>
    </div>
  );
};

const CommnetRoot = (props: TCommentRoot) => {
  const { review, handleReply, userId, handleDel, isAuthor } = props;
  return (
    <div className={style["commentRender"]}>
      <div className={style["avator"]}>
        <div className={style["avatorImg"]}>
          <Avatar src={`${SEVER_URL}${review.userHead}`} />
        </div>
      </div>
      <div className={style["main"]}>
        <div className={style["userName"]}>
          {review.userId === isAuthor ? (
            <>
              {review.userName}
              <Tag color="red">发布人</Tag>
            </>
          ) : (
            review.userName
          )}
          {/*  {review?.userName ? review?.userName : "匿名用户"} */}
        </div>
        <div
          contentEditable
          className={style["content"]}
          dangerouslySetInnerHTML={{
            __html: review?.content as string | TrustedHTML,
          }}
        ></div>
        <div className={style["footer"]}>
          <span className={style["date"]}>{review?.createTime}</span>
          <Space>
            <span
              className={style["review"]}
              onClick={() =>
                handleReply?.(review?.id, review?.userId, review?.postId)
              }
            >
              回复
            </span>
            {userId == review.userId && (
              <span
                className={style["review"]}
                onClick={() => handleDel?.(review.id)}
              >
                删除
              </span>
            )}
          </Space>
        </div>
      </div>
    </div>
  );
};
const CommentReply = (props: TCommentReply) => {
  const { reply, handleReply, userId, handleDel, isAuthor } = props;
  return (
    <div className={style["commentReplyRender"]}>
      <div className={style["replyRender"]}>
        <div className={style["avatarCtn"]}>
          {reply.userHead ? (
            <Avatar src={`${SEVER_URL}${reply.userHead}`} size={24} />
          ) : (
            <Avatar icon={<UserOutlined />} size={24}></Avatar>
          )}
        </div>
        <div className={style["main"]}>
          <div className={style["userName"]}>
            <Space>
              {/* {reply.userName ? reply.userName : "匿名用户"} */}
              {reply.userId === isAuthor ? (
                <>
                  {reply.userName}
                  <Tag color="red">发布人</Tag>
                </>
              ) : (
                reply.userName
              )}
              <span
                className={style["replyText"]}
                onClick={() =>
                  handleReply?.(reply.id, reply.userId, reply.postId)
                }
              >
                回复
              </span>
              {reply.replyUserHead ? (
                <Avatar src={`${SEVER_URL}${reply.replyUserHead}`} size={24} />
              ) : (
                <Avatar icon={<UserOutlined />} size={24}></Avatar>
              )}
              {/* TODO:返回被回复人 id */}
              {reply.replyUserId === isAuthor ? (
                <>
                  {reply.replyUserName}
                  <Tag color="red">发布人</Tag>
                </>
              ) : (
                reply.replyUserName
              )}
              {/* {reply.replyUserName ? reply.replyUserName : "匿名用户"} */}
            </Space>
          </div>
          <div
            contentEditable
            className={style["content"]}
            dangerouslySetInnerHTML={{ __html: reply.content }}
          ></div>
          <div className={style["footer"]}>
            <span className={style["date"]}>{reply.updateTime}</span>
            <Space>
              <span
                className={style["review"]}
                onClick={() =>
                  handleReply?.(reply.rootId, reply.userId, reply.postId)
                }
              >
                回复
              </span>
              {userId == reply.userId && (
                <span
                  className={style["review"]}
                  onClick={() => handleDel?.(reply.id)}
                >
                  删除
                </span>
              )}
            </Space>
          </div>
        </div>
      </div>
    </div>
  );
};
